package com.CloudDream.Command.Player;

import com.CloudDream.Inventory.InventoryItem;
import com.CloudDream.MoonCake;
import com.CloudDream.Util.TextUtil;
import com.handy.lib.command.IHandyCommandEvent;
import com.handy.lib.util.BaseUtil;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;

public class GiveGiftCommand implements IHandyCommandEvent {
    private MoonCake instance = MoonCake.getInstance();

    @Override
    public String command() {
        return "givegift";
    }

    @Override
    public String permission() {
        return "mooncake.givegift";
    }

    @Override
    public void onCommand(CommandSender commandSender, Command command, String s, String[] args) {
        if(BaseUtil.isNotPlayer(commandSender).booleanValue()){
            commandSender.sendMessage(MoonCake.prefix + "§7该命令只能由玩家执行");
            return;
        }
        if(args.length < 2){ return; }

        ItemStack item;
        Player p = (Player) commandSender;
        item = p.getItemInHand();
        String m = "Message.";

        (new BukkitRunnable(){
            public void run() {
                if (!item.equals(InventoryItem.getGift())) {
                    p.sendMessage(MoonCake.prefix + TextUtil.ReplaceText(m + ".Error-4"));
                }

                if (item.equals(InventoryItem.getGift())) {
                    Player t = Bukkit.getPlayer(args[1]);
                    if (t == null) {
                        p.sendMessage(MoonCake.prefix + TextUtil.ReplacePlayer(".Error-1", args[1]));
                        return;
                    }

                    if (t == p) {
                        p.sendMessage(MoonCake.prefix + TextUtil.ReplaceText(m + ".Error-6"));
                        return;
                    }
                    p.setItemInHand(new ItemStack(Material.AIR));
                    p.sendMessage(MoonCake.prefix + TextUtil.ReplacePlayer(m + ".Send-Gift", p.getName()));
                    t.getInventory().addItem(item);
                    t.sendMessage(MoonCake.prefix + TextUtil.ReplacePlayer(m + ".Send-Gift", t.getName()));
                    Bukkit.broadcastMessage(instance.getConfig().getString(m + ".Get-Gift-Broadcast").replace("&", "§").replace("{player1}", p.getName()).replace("{player2}", t.getName()));
                }
            }
        }).runTaskAsynchronously(MoonCake.getInstance());

    }
}
